import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';
import { FileModel } from '@/models/file.model';
import { getFileGroups } from '@/services/upload.service';

export interface UploadDialogConfig {
    multi?: boolean;
    callback: (file: FileModel[]) => void;
}

@Module({ name: 'uploadDialog', dynamic: true, namespaced: true, store })
export default class UploadDialogStore extends VuexModule {
    private _info = {} as UploadDialogConfig;
    private _files: FileModel[] = [];
    private _visible: boolean = false;
    private _groups: any[] = [
        { id: 0, name: '默认分组' }
    ];

    public get visible(): boolean {
        return this._visible;
    }

    public get info(): UploadDialogConfig {
        return this._info;
    }

    public get files(): FileModel[] {
        return this._files;
    }

    public get groups(): any[] {
        return this._groups;
    }

    @Action
    public getGroup() {
        if (this._groups.length > 1) {
            return;
        }
        getFileGroups()
            .then(result => {
                this.context.commit('updateGroups', result.data.items);
            })
    }

    @Mutation
    private updateGroups(data: any[]) {
        this._groups = [ ...this._groups, ...data ];
    }

    /**
     * 打开上传窗体
     * @param data
     */
    @Mutation
    public open(data: UploadDialogConfig) {
        this._info = {
            ...data,
        }
        this._visible = true;
    }

    /**
     * 添加文件
     * @param file
     */
    @Mutation
    public addFile(file: FileModel) {
        this._files.push(file);
    }

    /**
     * 删除文件
     * @param idx
     */
    @Mutation
    public removeFile(idx: number) {
        this._files.splice(idx, 1);
    }

    @Mutation
    public clearFile() {
        this._files = [];
    }

    /**
     * 执行回调
     */
    @Mutation
    public callback() {
        this._info.callback(this._files);
    }

    /**
     * 关闭窗体
     */
    @Mutation
    public close() {
        this._visible = false;
    }

    /**
     * 销毁当前窗体数据
     */
    @Mutation
    public dispose() {
        this._info = {} as any;
        this._files = [];
    }
}

export const UploadDialogModule = getModule(UploadDialogStore);
